import 'dart:collection';
import 'dart:convert';

List<ArtistModel> artistFromJson(String str) => List<ArtistModel>.from(
    json.decode(str).map((x) => ArtistModel.fromJson(x)));

String artistToJson(List<ArtistModel> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ArtistModel extends LinkedListEntry<ArtistModel> {
  ArtistModel({required this.k, required this.v, this.m});

  String k;
  String v;
  String? m;

  factory ArtistModel.fromJson(Map<String, dynamic> json) => ArtistModel(
        k: json["k"],
        v: json["v"],
        m: json["m"],
      );

  Map<String, dynamic> toJson() => {
        "k": k,
        "v": v,
        "m": m,
      };

  // 计算artistBin中1的个数
  int countOnesInBinary() {
    if (v.isEmpty) {
      return 0;
    }
    if (v.startsWith("U")) {
      return -1;
    }
    int dec = int.parse(v.substring(1), radix: 36);
    return dec.toRadixString(2).split('').where((c) => c == '1').length;
  }
}

extension ArtistModelExtension on List<ArtistModel> {
  List<ArtistModel> sortArtistsByAsc() {
    sort((a, b) {
      return a.countOnesInBinary().compareTo(b.countOnesInBinary());
    });
    return this;
  }

  List<ArtistModel> sortArtistsByDesc() {
    sort((a, b) {
      return b.countOnesInBinary().compareTo(a.countOnesInBinary());
    });
    return this;
  }

  List<ArtistModel> filterSoloArtist() {
    removeWhere((artist) => artist.countOnesInBinary() > 1);
    return this;
  }
}
